<?php

namespace App\Http\Controllers\Wechat\WechatServiceAccount;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use Illuminate\Support\Facades\Log;


class OrderController extends Controller
{
    /**
     * 订单列表
     */
    public function index(Request $request)
    {
        $userId = auth('wechat')->id();
        Log::info('Wechat User ID: ' . $userId);

        // 添加用户ID检查
        if (!$userId) {
            Log::error('获取用户ID失败，无法查询订单');
            return view('wechat.service_account.member_center.orders', ['orders' => collect()]);
        }

        $orders = Order::with('items')
            ->where('wechat_service_account_user_id', $userId)
            ->orderByDesc('id')
            ->paginate(10);

        return view('wechat.service_account.member_center.orders', compact('orders'));
    }

    /**
     * 取消订单
     */
    public function cancel(Request $request, $orderId)
    {
        // 添加日志记录方法调用
        Log::info('取消订单方法被调用', [
            'order_id' => $orderId,
            'user_id' => auth('wechat')->id(),
            'request_data' => $request->all()
        ]);

        $order = Order::findOrFail($orderId);

        // 检查订单状态是否为未支付
        if ($order->status !== '未支付') {
            Log::warning('订单取消失败：非未支付状态', ['order_id' => $orderId, 'current_status' => $order->status]);
            return back()->with('error', '只有未支付的订单可以取消');
        }

        // 更新订单状态为已取消
        $order->update(['status' => '已取消']);
        Log::info('订单取消成功', ['order_id' => $orderId]);

        return back()->with('success', '订单已取消');
    }

    /**
     * 查询订单支付状态
     */
    public function checkPaymentStatus(Request $request, $orderId)
    {
        try {
            $order = Order::where('id', $orderId)
                ->where('wechat_service_account_user_id', auth('wechat')->id())
                ->firstOrFail();

            if ($order->status === 'paid') {
                return response()->json([
                    'success' => true,
                    'status' => 'paid',
                    'message' => '订单已支付'
                ]);
            } else {
                return response()->json([
                    'success' => true,
                    'status' => $order->status,
                    'message' => '订单未支付'
                ]);
            }
        } catch (\Exception $e) {
            Log::error('查询支付状态失败', [
                'order_id' => $orderId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '查询失败'
            ]);
        }
    }
}
